import { useState, useEffect, useRef, RefObject } from 'react';
import { Document, Page } from 'react-pdf'
import moment from 'moment'
import { message, Form, Input, Select, DatePicker, Button, Space, Skeleton, Dropdown, Menu, FormInstance } from 'antd';
import style from './index.module.less'
import { confirmAction } from '@js/tool'
import { download } from '@js/downloadRename'
import EditorPart from './components/editorPart'
import { PDFSchema } from '@src/components/schema/pdf';
import { PDFParamSchema } from '@src/components/schema/pdf';
import { getFileRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool';
import { useDispatch } from 'react-redux';
import { addResizeEvent, delResizeEvent } from '@redux/actions/globalEvent';

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

function Loading () {
  return (
    <div className={style['empty-page']}>
      <Skeleton active paragraph={{ rows: 6 }} />
    </div>
  )
}

function initDoc (d: any) {}

// 根据id获取文书
async function getFileById (
  caseid: string,
  fileid: string,
  readonly: boolean,
  initState: () => void,
  setFile: (v: PDFSchema) => void,
  setIsSeal: (v: boolean) => void,
  setTempSeal: (v: string | null) => void,
  setFormParamsHidden: (v: PDFParamSchema[]) => void,
  setFormParams: (v: PDFParamSchema[]) => void,
  setFormInitData: (v: { [k: string]: any }) => void,
  setFormParamsMap: (v: { [k: string]: PDFParamSchema }) => void,
) {
  const [e, d] = await awaitWrap(getFileRequest(caseid, fileid))
  if (e === null && d !== null) {
    initState()
    if (!d.pdf_path) {
      return setTimeout(() => {
        getFileById(caseid, fileid, readonly, initState, setFile, setIsSeal, setTempSeal, setFormParamsHidden, setFormParams, setFormInitData, setFormParamsMap)
      }, 2000)
    }
    d.pdf_path = d.pdf_path.replace(/^.*\/upload/, '/upload')
    setFile(d)
    setIsSeal(Boolean(d.seal))
    setTempSeal(d.temp_seal)
    initFormParamsData(setFormParamsHidden, setFormParams, setFormInitData, setFormParamsMap, d)
  }
}

// 根据文书参数和文书模板参数生成表单参数
function initFormParamsData (
  setFormParamsHidden: (v: PDFParamSchema[]) => void,
  setFormParams: (v: PDFParamSchema[]) => void,
  setFormInitData: (v: { [k: string]: any }) => void,
  setFormParamsMap: (v: { [k: string]: PDFParamSchema }) => void,
  file: PDFSchema
) {
  window.moment = moment
  const formInitData: { [k: string]: any } = {}
  const formParamsMap: { [k: string]: PDFParamSchema } = {}
  const formParamsHidden = (file.parameters || []).filter(li => li.parm_input_type === '隐藏域')
  const formParams = (file.parameters || []).filter(li => li.parm_input_type !== '隐藏域').map(li => {
    const v = li.parm_value
    const t = li.parm_input_type
    const k = li.parm_key
    const td = li.parm_type_data
    if (t === '多选选择器' && v) {
      formInitData[k] = v.split(',').filter(li => li !== '')
    } else if (t === '时间选择器' && v) {
      let filterV = encodeURIComponent(li.parm_value)
      filterV = filterV.replace(/%C2%A0/g, '%20')
      filterV = decodeURIComponent(filterV)
      formInitData[k] = moment(filterV, td || 'YYYY年MM月DD日')
    } else {
      formInitData[k] = v
    }
    formParamsMap[k] = li

    return li
  })
  setFormParamsHidden(formParamsHidden)
  setFormParams(formParams)
  setFormInitData(formInitData)
  setFormParamsMap(formParamsMap)
}

function setPDFWidth (docBoxRef: RefObject<HTMLDivElement>, setWidth: (v: number) => void, setHeight: (v: number) => void, setReady: (v: boolean) => void) {
  const w = docBoxRef.current?.offsetWidth
  setWidth(w || 0)
  setHeight((w || 0) * 1.4140625)
  setReady(true)
}

interface Props {
  meta?: { [k: string]: any }
}

function Main ({ meta }: Props) {
  const [file, setFile] = useState<PDFSchema | null>(null)
  const [isSeal, setIsSeal] = useState(false)
  const [tempSeal, setTempSeal] = useState<string | null>(null)
  const [formParamsHidden, setFormParamsHidden] = useState<PDFParamSchema[]>([])
  const [formParams, setFormParams] = useState<PDFParamSchema[]>([])
  const [formParamsMap, setFormParamsMap] = useState<{[k: string]: PDFParamSchema}>({})
  const [formInitData, setFormInitData] = useState<{[k: string]: any}>({})
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)
  const [numPages, setNumPages] = useState(0)
  const [ready, setReady] = useState(false)
  const [nums, setNums] = useState<number[]>([])
  const [readonly, setReadonly] = useState(false)
  const [id, setId] = useState('')
  const [fileid, setFileid] = useState('')
  const docBoxRef = useRef<HTMLDivElement>(null)
  const formRef = useRef<FormInstance>(null)
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(addResizeEvent({ name: `resizePdf-${fileid}`, handle: () => setPDFWidth(docBoxRef, setWidth, setHeight, setReady) }))
    return () => {
      dispatch(delResizeEvent(`resizePdf-${fileid}`))
    }
  }, [])
  
  useEffect(() => {
    if (meta) {
      setReadonly(!!meta.readonly)
      setId(meta.caseid)
      setFileid(meta.fileid)
    }
  }, [meta])

  useEffect(() => {
    const l = []
    for (let i = 0; i < numPages; i++) {
      l.push(i)
    }
    setNums(l)
  }, [numPages])

  useEffect(() => {
    if (id && fileid) {
      getFileById(id, fileid, readonly, initState, setFile, setIsSeal, setTempSeal, setFormParamsHidden, setFormParams, setFormInitData, setFormParamsMap)
    }
  }, [id, fileid, readonly])


  function initState () {
    setFile(null)
    setIsSeal(false)
    setFormParamsHidden([])
    setFormParams([])
    setFormParamsMap({})
    setFormInitData({})
  }

  return (
    <div className={style.container}>
      <div className={style.inner}>
        <div className={style['left-box']}>
          <div className={style['pdf-box']} ref={docBoxRef}>
            {
              file ? (
                <Document
                  loading={<Loading />}
                  file={`${file.pdf_path}`}
                  onLoadSuccess={(e) => {
                    setNumPages(e.numPages)
                    setPDFWidth(docBoxRef, setWidth, setHeight, setReady)
                  }}
                  error='文书生成失败，请点击“重新生成”操作。'
                  // options={{ cMapUrl: 'cmaps/', cMapPacked: true }}
                >
                 {
                  ready && (
                    nums.map(i => {
                      return (
                        <div className={style.page} key={i}>
                          <Page pageNumber={i + 1} width={width} height={height} renderTextLayer={false} renderAnnotationLayer={false} />
                        </div>
                      )
                    })
                  )
                 }
                </Document>
              ) : <Loading />
            }
          </div>
        </div>
        <EditorPart caseid={id} fileid={fileid} file={file} readonly={readonly} formParams={formParams} formInitData={formInitData} tempSeal={tempSeal} isSeal={isSeal} formParamsHidden={formParamsHidden} formParamsMap={formParamsMap} refreshFn={() => {
          getFileById(id, fileid, readonly, initState, setFile, setIsSeal, setTempSeal, setFormParamsHidden, setFormParams, setFormInitData, setFormParamsMap)
        }} />
      </div>
    </div>
  )
}

export default Main
